package com.tj.jinzao.activity;

import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tj.jinzao.R;
import com.tj.jinzao.api.ApiRetrofit;
import com.tj.jinzao.api.ApiService;
import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.BaseActivity;
import com.tj.jinzao.callback.IFallowView;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.fragment.MyCommentListFragment;
import com.tj.jinzao.fragment.MyLiveListFragment;
import com.tj.jinzao.fragment.PersonArticleListFragment;
import com.tj.jinzao.manager.UserManager;
import com.tj.jinzao.model.FollowFan;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.model.User;
import com.tj.jinzao.presenter.FollowFanPresenter;
import com.tj.jinzao.utils.DisplayUtil;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.widgets.RoundedImageView;

import java.lang.reflect.Field;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 个人主页首页
 * Created by wjy on 2018/12/10.
 */
public class PersonArticleActivity extends BaseActivity<FollowFanPresenter> implements IFallowView<List<FollowFan>> {

    private FragmentPagerAdapter mPagerAdapter;
    @BindView(R.id.viewPager)
    ViewPager mViewPaper;
    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.tv_order)
    TextView mOrderView;
    @BindView(R.id.iv_arrow)
    ImageView mArrowView;
    @BindView(R.id.iv_head)
    RoundedImageView mHeadView;
    @BindView(R.id.tv_name)
    TextView mNickNameView;
    @BindView(R.id.tv_vip)
    TextView mVipView;
    @BindView(R.id.tv_intro)
    TextView mIntroView;
    @BindView(R.id.tv_edit)
    TextView mEditView;
    @BindView(R.id.tv_label)
    TextView mLabelView;
    protected ApiService mApiService = ApiRetrofit.getInstance().getApiService();

    private CompositeSubscription mCompositeSubscription;
    public void detachView() {
        onUnsubscribe();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        detachView();

    }

    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

    private int mPrevPosition = -1;
    private int mPosition = 0;

    private User mUser;

    private Fragment mCurrentFragment;

    private boolean mRevert = true;

    @Override
    protected FollowFanPresenter createPresenter() {
        return new FollowFanPresenter(this);
    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_person_layout;
    }

    @Override
    protected void setupView() {
        super.setupView();
        setTitleText("");
        setAdapter();
    }
    public void getUserFollow() {
        long id = UserManager.getInstance().getUser().getId();
        addSubscription(mApiService.getIsFollow(id,mUser.getId())
                , new SubscriberCallBack<Boolean>(PersonArticleActivity.this) {
                    @Override
                    protected void onSuccess(Boolean b) {
                        if (mUser.getId() != UserManager.getInstance().getUser().getId()) {
                            mEditView.setText(b ? "已关注" : "关注");
                        }

                    }

                    @Override
                    protected void onFailure(ResultResponse response) {
                    }

                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mUser = (User) getIntent().getSerializableExtra("user");
        if(mUser.getId()==UserManager.getInstance().getUser().getId()||mUser == null){
            mUser=UserManager.getInstance().getUser();
        }
        getUserFollow();
        bindDataView();
    }

    @Override
    protected int getLeftButtonResId() {
        return R.mipmap.ic_back;
    }

    @OnClick(R.id.tv_edit)
    public void edit() {
        if (mUser.getId() == UserManager.getInstance().getUser().getId()) {
            startActivity(new Intent(this, PersonInfoActivity.class));
        } else {
            mPresenter.followUser(mUser.getId());
        }
    }

    @OnClick(R.id.ll_order_layout)
    public void changeOrder() {
        mRevert = !mRevert;
        if (mRevert) {
            mArrowView.setImageResource(R.mipmap.arrow_green_down);
            mOrderView.setText("时间倒序");
        } else {
            mArrowView.setImageResource(R.mipmap.arrow_green_up);
            mOrderView.setText("时间顺序");
        }
        if(personArticleListFragment1!=null){
            personArticleListFragment1.setRevert(mRevert);
        }
        if(personArticleListFragment2!=null){
            personArticleListFragment2.setRevert(mRevert);
        }
        if(personArticleListFragmen3!=null){
            personArticleListFragmen3.setRevert(mRevert);
        }
        if(myCommentListFragment!=null){
            myCommentListFragment.setRevert(mRevert);
        }
        if(myLiveListFragment!=null){
            myLiveListFragment.setRevert(mRevert);
        }
//        if (mCurrentFragment instanceof PersonArticleListFragment) {
//            ((PersonArticleListFragment) mCurrentFragment).setRevert(mRevert);
//        }else  if (mCurrentFragment instanceof MyLiveListFragment){
//            ((MyLiveListFragment) mCurrentFragment).setRevert(mRevert);
//        }else  if (mCurrentFragment instanceof MyCommentListFragment){
//            ((MyCommentListFragment) mCurrentFragment).setRevert(mRevert);
//        }
    }

    private void bindDataView() {
        Glide.with(this).load(Constant.IMAGE_PREFIX + mUser.getImgurl()).into(mHeadView);
        mNickNameView.setText(TextUtils.isEmpty(mUser.getNickname()) ? "" : mUser.getNickname());
        mVipView.setText("V" + mUser.getLevel());
        mLabelView.setText(mUser.getTags());
        if (mUser.getId() != UserManager.getInstance().getUser().getId()) {
            mEditView.setText(mUser.isHasFollow() ? "已关注" : "关注");
        }
        mIntroView.setText(TextUtils.isEmpty(mUser.getSignature()) ? "一句话介绍…" : mUser.getSignature());
    }
    private PersonArticleListFragment personArticleListFragment1,personArticleListFragment2,personArticleListFragmen3;
    private MyLiveListFragment myLiveListFragment;
    private MyCommentListFragment myCommentListFragment;

    public void setAdapter() {
        mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(final int position) {
                switch (position) {
                    case 0:
                        if(personArticleListFragment1==null){
                            personArticleListFragment1=PersonArticleListFragment.newInstance(mUser.getId(), position);
                        }
                        return personArticleListFragment1;
                    case 1:
                        if(personArticleListFragment2==null){
                            personArticleListFragment2=PersonArticleListFragment.newInstance(mUser.getId(), position);
                        }
                        return personArticleListFragment2;
                    case 2:
                        if(personArticleListFragmen3==null){
                            personArticleListFragmen3=PersonArticleListFragment.newInstance(mUser.getId(), position);
                        }
                        return personArticleListFragmen3;
                    case 3:
                        if(myLiveListFragment==null){
                            myLiveListFragment=MyLiveListFragment.newInstance(mUser.getId());
                        }
                        return myLiveListFragment;
                    case 4:
                        if(myCommentListFragment==null){
                            myCommentListFragment=MyCommentListFragment.newInstance();
                        }
                        return myCommentListFragment;
                }
                return null;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {
                    case 0:
                        return "日记";
                    case 1:
                        return "视频";
                    case 2:
                        return "话题";
                    case 3:
                        return "直播";
                    case 4:
                        return "评论";
                }
                return "";
            }

            @Override
            public int getCount() {
                return 5;
            }


            @Override
            public void setPrimaryItem(ViewGroup container, int position, Object object) {
                super.setPrimaryItem(container, position, object);
                if (object == null || (mPrevPosition == position && mCurrentFragment != null))
                    return;
                mPrevPosition = position;
                mCurrentFragment = (Fragment) object;
                if (mCurrentFragment instanceof PersonArticleListFragment) {
                    ((PersonArticleListFragment) mCurrentFragment).setRevert(mRevert);
                }
                if (null == mCurrentFragment) return;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                super.destroyItem(container, position, object);
                getSupportFragmentManager().beginTransaction()
                        .remove((Fragment) object).commitAllowingStateLoss();
                try {
                    Field parentFragment = Fragment.class.getDeclaredField("mParentFragment");
                    parentFragment.setAccessible(true);
                    parentFragment.set(object, null);
                } catch (NoSuchFieldException ignored) {
                } catch (IllegalAccessException ignored) {
                }
            }
        };
        mViewPaper.setAdapter(mPagerAdapter);
        mViewPaper.setCurrentItem(mPosition);
        mViewPaper.setOffscreenPageLimit(4);
        mTabLayout.setupWithViewPager(mViewPaper);
        View view1= LayoutInflater.from(PersonArticleActivity.this).inflate(R.layout.item_person_article,null);
        TextView txt1=view1.findViewById(R.id.txt);
        txt1.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtil.dip2px(PersonArticleActivity.this,12));
        txt1.setText("日记");
        View view2= LayoutInflater.from(PersonArticleActivity.this).inflate(R.layout.item_person_article,null);
        TextView txt2=view2.findViewById(R.id.txt);
        txt2.setText("视频");
        txt2.setTextColor(getResources().getColor(R.color.live_config_unselect));
        txt2.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtil.dip2px(PersonArticleActivity.this,12));
        View view3= LayoutInflater.from(PersonArticleActivity.this).inflate(R.layout.item_person_article,null);
        TextView txt3=view3.findViewById(R.id.txt);
        txt3.setTextColor(getResources().getColor(R.color.live_config_unselect));
        txt3.setText("话题");
        txt3.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtil.dip2px(PersonArticleActivity.this,12));
        View view4= LayoutInflater.from(PersonArticleActivity.this).inflate(R.layout.item_person_article,null);
        TextView txt4=view4.findViewById(R.id.txt);
        txt4.setTextColor(getResources().getColor(R.color.live_config_unselect));
        txt4.setText("直播");
        txt4.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtil.dip2px(PersonArticleActivity.this,12));
        View view5= LayoutInflater.from(PersonArticleActivity.this).inflate(R.layout.item_person_article,null);
        TextView txt5=view5.findViewById(R.id.txt);
        txt5.setText("评论");
        txt5.setTextColor(getResources().getColor(R.color.live_config_unselect));
        txt5.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtil.dip2px(PersonArticleActivity.this,12));
        mTabLayout.getTabAt(0).setCustomView(view1);
        mTabLayout.getTabAt(1).setCustomView(view2);
        mTabLayout.getTabAt(2).setCustomView(view3);
        mTabLayout.getTabAt(3).setCustomView(view4);
        mTabLayout.getTabAt(4).setCustomView(view5);
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
               TextView txt= tab.getCustomView().findViewById(R.id.txt);
                txt.setTextColor(getResources().getColor(R.color.live_config_select));
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                TextView txt= tab.getCustomView().findViewById(R.id.txt);
                txt.setTextColor(getResources().getColor(R.color.live_config_unselect));

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void onRequestSuccessPage(int currentPage, int allPage, int allSize) {

    }

    @Override
    public void onReload(Object tag) {

    }

    @Override
    public Activity getContext() {
        return this;
    }

    @Override
    public void onRequestSuccess(List<FollowFan> followFans) {
    }

    @Override
    public void onRequestNoData(String message) {

    }

    @Override
    public void onRequestError(String error_message) {

    }

    @Override
    public void onAttentSuccess(List<FollowFan> followFans) {
        if (followFans.size() == 1) {
            if(mEditView.getText().toString().equals("已关注")){
                mEditView.setText("关注");
            }else {
                mEditView.setText("已关注");
            }
//            mEditView.setText(followFans.get(0).getFollowUid() == 1 ? "已关注" : "关注");
        }

    }

    @Override
    public void onAttentFailed(String msg) {
        if(msg==null){
            return;
        }
        ToastUtils.showToast(this,msg);
    }
}
